package cn.com.jit;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Stack;

public class CodeProcessor {

    public static void processDirectory(String directoryPath) {
        File directory = new File(directoryPath);
        if (!directory.exists() || !directory.isDirectory()) {
            System.err.println("Invalid directory path: " + directoryPath);
            return;
        }

        Stack<File> directories = new Stack<>();
        directories.push(directory);

        while (!directories.isEmpty()) {
            File currentDir = directories.pop();
            File[] files = currentDir.listFiles();
            if (files != null) {
                Arrays.stream(files).forEach(file -> {
                    if (file.isDirectory()) {
                        directories.push(file);
                    } else {
                        processFile(file);
                    }
                });
            }
        }
    }


    private static void processFile(File file) {
        if (file.isDirectory()) {
            processDirectory(file.getAbsolutePath());
        } else {
            String fileName = file.getName();
            String extension = getExtension(fileName);
            List<SqlVo> sqls =FileProcessorFactory.getProcessor(extension).processFile(file);
            if (null != sqls) {
                sqls.forEach(sql -> {
                    List<String> columns = SQLColumnExtractor.extractColumnNames(sql.getSql());
                    //循环colunms，对其元素做ReservedWordChecker检查
                    Map<String, String> checkResultMap =  ReservedWordChecker.getInstance().checkStringsInDictionaries(columns);
                    if(null!= checkResultMap&&!checkResultMap.isEmpty()){
                        System.out.println(sql.getFilePath() + "[:]" + sql.getLineNo() + ":" + sql.getSql() + ":" + checkResultMap);
                    }
                });
            }
        }
    }

    private static String getExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex == -1) {
            return "";
        }
        return fileName.substring(lastDotIndex + 1).toLowerCase();
    }
    public static void main(String[] args) {
        String directoryPath = "D:\\JIT_workspaces\\workspace\\pki508\\ra\\";
//        String directoryPath = "D:\\JIT_workspaces\\workspace\\FCMS_3.2\\platform-fcms-provide\\modules\\fcms-business";
        processDirectory(directoryPath);
    }
}
